<!-- 瀑布流布局 -->
<template>
  <view class="container">
    <view
      :id="`cont_${index + 1}`"
      class="cont-box"
      :style="{ width: widthCalc, 'margin-left': index === 0 ? 0 : marginCalc }"
      v-for="(numVal, index) in flowData.column"
      :key="numVal">
      <view class="item-box" v-for="(item, j) in flowData[`column_${index + 1}`]" :key="j" @click="handleDetails(item.id)">
        <view class="item-img">
          <image :src="item.bannerList[0]" mode="widthFix" lazy-load @load="imgLoad(item)" @error="imgError(item)" />
          <!-- <image :src="item.bannerList[0]" mode="widthFix" lazy-load /> -->
          <image src="../../static/ar.svg"/>
        </view>
        <view class="item-title">{{item.title}}</view>
        <view class="item-auth">
          <view class="auth-name">
            <image :src="item.userAvatar" />
            <text>{{item.userName}}</text>
          </view>
          <view class="like-num" @click.stop="changeLike(item.id,item.isLike,index)">
            <image v-if="item.isLike" src="../../static/like.svg"/>
            <image v-else src="../../static/no-like.svg"/>
            <text>{{item.likes}}</text>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>
 
<script setup>
  import { ref,reactive, computed, getCurrentInstance, onMounted,watch,nextTick } from "vue";
	import { artSaveLike } from '@/api/posting.js'
	import request from '@/http/request.js';
  const props = defineProps({
		dataList: {
			type: Array,
			default: []
		},
		isOnePage: {
			type: Boolean
		},
    //是否显示草稿箱
    isShowDrafts:{
      type: Boolean,
      default: false
    }
	});
  const emit = defineEmits([
		"refresh",
	]);

  const _this = getCurrentInstance();
  const flowData = reactive({
    list: [], // 数据值
    column: 2, // 瀑布列数
    columnSpace: 0.7, // 瀑布列宽间距
    showColumn_1:[],
    showColumn_2:[]
  });

  computed(() => {

  })


  /* 数据赋值 */
  // flowData.list = JSON.parse(JSON.stringify(props.dataList));

  watch(() => props.dataList, async (newVal,oldVal) => {
    // console.log('row props.dataList 变化   newVal',newVal)
    // console.log('row props.dataList 变化   oldVal',oldVal)
    let startIndex = 0
    // console.log('row props.dataList 变化   props.isOnePage',props.isOnePage)
    if(props.isOnePage){
      for (let i = 1; i <= flowData.column; i++) {
        flowData[`column_${i}`] = [];
      }
    }
    if(!props.isOnePage && oldVal?.length > 0){
      startIndex = oldVal.length
    }

    const dataList = JSON.parse(JSON.stringify(newVal))
    flowData.list = dataList;
    // /* 初始化每一列的数据 */
    // for (let i = 1; i <= flowData.column; i++) {
    //   flowData[`column_${i}`] = [];
    // }
    await nextTick()
    initValue(startIndex);
	}, 
  {
    immediate: true
  }
  );
  /* 生命周期函数-实例被挂载后调用 */
  onMounted(() => {
    /* 初始化每一列的数据 */
    // console.log('初始化')
    for (let i = 1; i <= flowData.column; i++) {
      flowData[`column_${i}`] = [];
    }
  });

  /* 计算列宽 */
  const widthCalc = computed(() => {
    return `${100 / flowData.column - flowData.columnSpace}%`;
  });
  /* 计算 margin 外边距 */
  const marginCalc = computed(() => {
    const columnWidth = 100 / flowData.column - flowData.columnSpace;
    return `${(100 - columnWidth.toFixed(5) * flowData.column) / (flowData.column - 1)}%`;
  });
  /* 获取最小值的对象 */
  const getMinObj = (a, s) => {
    let m = a[0][s];
    let mo = a[0];
    for (let i = a.length - 1; i >= 0; i--) {
      if (a[i][s] < m) m = a[i][s];
    }
    mo = a.filter(i => i[s] === m);
    return mo[0];
  };
  /* 计算每列的高度 */
  const getMinColumnHeight = () => {
    return new Promise(resolve => {
      const heightArr = [];
      for (let i = 1; i <= flowData.column; i++) {
        uni
          .createSelectorQuery()
          .in(_this)
          .select(`#cont_${i}`)
          .boundingClientRect(res => {
            heightArr.push({ column: i, height: res.height });
          })
          .exec(() => {
            if (flowData.column <= heightArr.length) {
              resolve(getMinObj(heightArr, "height"));
            }
          });
      }
    });
  }
  /* 初始化瀑布流数据 */
  const initValue = async (i) => {
    if (i >= flowData.list.length) return false;
    // 判断list length 是否为单数  并且 是否是最后一个  就直接排列在第一列 
    if(flowData.list.length%2 != 0 && i === flowData.list.length-1){
      // console.log('最后一个  并且为单数')
      flowData[`column_1`].push({
        ...flowData.list[i],
        index: i
      });
      return;
    }
    const minHeightRes = await getMinColumnHeight();
    // console.log('minHeightRes',minHeightRes.column);
    flowData[`column_${minHeightRes.column}`].push({
      ...flowData.list[i],
      index: i
    });
  }
  // /* 图片加载完成 */
  const imgLoad = (item) => {
    const i = item.index;
    initValue(i + 1); // 加载下一条数据
  }
  /* 图片加载失败 */
  const imgError = (item) => {
    const i = item.index;
    initValue(i + 1); // 加载下一条数据
  }
  
  // 查看详情
	const handleDetails = (id) => {
		uni.navigateTo({
			url:`/pages/postDetails/index?id=${id}`
		})
	}

	//帖子点赞
  const changeLike = async (id,isLike,columnIndex) => {
		let res = await artSaveLike({
			dataId:id,
			status:isLike ? 2 : 1,  //1点赞  2 取消点赞
			type:1    	//类型:1帖子,2评论
		})

    let arr = flowData[`column_${columnIndex + 1}`]
    for (let i = 0; i < arr.length; i++) {
      if(arr[i].id === id){
        arr[i].isLike = !arr[i].isLike
        isLike ? arr[i].likes-- : arr[i].likes++
      }
    }
    // emit('refresh',() => {
		// 	uni.showToast({
		// 		title: isLike?'已取消点赞':'点赞成功',
		// 		icon:'none',
		// 		duration: 2000
		// 	});
		// })
	}
</script>
 
<style lang="scss" scoped>
.container {
  /* height: calc(100vh - (var(--status-bar-height) + 216rpx));
	height: calc(100vh - (var(--status-bar-height) + 216rpx + env(safe-area-inset-bottom))); */
  height: auto;
  /* background-color: #F4F4F4; */
  padding: 0 10rpx;
  /* background: linear-gradient( 180deg, rgba(244,244,244,0) 0%, #F4F4F4 100%); */
  
  .cont-box {
    float: left;
    overflow: hidden;
    .item-box {
      width: 100%;
      padding-bottom: 24rpx;
			margin-bottom: 10rpx;
      background-color: white;
      .item-img{
				width: 360rpx;
				height: 480rpx !important;
        position: relative;

        image:nth-of-type(1){
          width: 100%;
          height: 100% !important;
        }
        image:nth-of-type(2){
          width: 46rpx;
          height: 46rpx;
          position: absolute;
          right: 10rpx;
          bottom: 10rpx;
        }
			}
			.item-title{
				width: 326rpx;
				font-weight: 400;
				font-size: 28rpx;
				color: #333333;
				margin: 24rpx 0 24rpx 17rpx;
        /* word-break: break-all; */
        /* white-space: nowrap;  */
        /* word-break: keep-all;  防止单词或连续数字在中间换行。 */
				@include text-overflow-many(2);
			}
			.item-auth{
				width: 326rpx;
				height: 36rpx;
				/* border: 1rpx solid red; */
				margin-left: 17rpx;
				@include flex(row,space-between);
				.auth-name{
					@include flex(row,flex-start);
					image{
						width: 36rpx;
						height: 36rpx;
						border-radius: 18rpx;
						margin-right: 12rpx;
					}
					text{
						font-weight: 400;
						font-size: 22rpx;
						color: #666666;
					}
				}
				.like-num{
					@include flex(row,flex-end);
					image{
						width: 28rpx;
						height: 28rpx;
						margin-right: 4rpx;
					}
					text{
						font-weight: 400;
						font-size: 22rpx;
						color: #666666;
					}
				}
			}
    }
  }
}

</style>